package org.example.reference;

import java.lang.ref.WeakReference;

/**
 * 只要触发了垃圾回收 第一次就会回收WeakReference
 * @author youshang
 * @date 2022/03/31 02:31
 **/
public class WeakReferenceTest {
    public static class User{
        public User(int id,String name){
            this.id = id ;
            this.name = name;
        }
        public int id;
        public String name;

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        //创建对象，建立弱引用
        WeakReference<SoftReferenceTest.User> zsReference = new WeakReference<>(new SoftReferenceTest.User(1, "zs"));
        //从软引用中重新获取强引用对象
        System.out.println(zsReference.get());

        System.gc();
        System.out.println("after GC:");
        //垃圾回收之后获得弱引用中的对象
        System.out.println(zsReference.get());
    }
}
